package com.lb.trac.web.json.transformer;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.beanutils.PropertyUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.xml.sax.SAXException;

import com.lb.trac.web.XmlColumnWrapper;
import com.lb.trac.web.XmlTableTransformerParser;


/**
 * classe che converte un array di utenti nel formato json
 * @author edoardo
 *
 */
public class BeanToJSONTableTransformer extends AbstractJSONTransformer {

	private XmlTableTransformerParser parser;
	@Override
	public <T> JSONObject javaObjectToJsonObject(T[] obj) {
		JSONArray result = new JSONArray();
		JSONObject jsonObject = null;
		try {
			Map<String, JSONArray> rootMap = new HashMap<String, JSONArray>();
			XmlColumnWrapper[] columnsDef = parser.parse();
			for (int i = 0; i < obj.length; i++) {
				Map<XmlColumnWrapper,Object> columnsMap = new TreeMap<XmlColumnWrapper, Object>();
				T t =  obj[i];
				try {
					for (int j = 0; j < columnsDef.length; j++) {
						XmlColumnWrapper c = columnsDef[j];
						Object value = PropertyUtils.getProperty(t, c.getPropertyName());
						columnsMap.put(c, value);
					}
					result.put(columnsMap);
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			rootMap.put("items", result);
			jsonObject=new JSONObject(rootMap);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		
		return jsonObject;
	}
	public XmlTableTransformerParser getParser() {
		return parser;
	}
	public void setParser(XmlTableTransformerParser parser) {
		this.parser = parser;
	}

}
